package com.yayawan.laomigame.callback;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.StrictMode;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.widget.Toast;


import com.mylhyl.acp.Acp;
import com.mylhyl.acp.AcpListener;
import com.mylhyl.acp.AcpOptions;
import com.yayawan.callback.YYWAnimCallBack;
import com.yayawan.callback.YYWApiCallback;
import com.yayawan.callback.YYWExitCallback;
import com.yayawan.callback.YYWPayCallBack;
import com.yayawan.callback.YYWUserCallBack;
import com.yayawan.domain.YYWOrder;
import com.yayawan.domain.YYWUser;
import com.yayawan.laomigame.App;
import com.yayawan.laomigame.Constant;
import com.yayawan.laomigame.TasksManagerActivity;
import com.yayawan.laomigame.WebViewActivity;
import com.yayawan.main.Kgame;
import com.yayawan.utils.DeviceUtil;
import com.yayawan.utils.Sputils;
import com.yayawan.utils.Yayalog;
import com.ycbjie.webviewlib.view.X5WebView;


import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import wendu.dsbridge.CompletionHandler;


public class LaomiGameApi {

    public static boolean isloginsuc = false;

    public static boolean isloginisshow = false;
    public Activity mActivity;

    public X5WebView mWebView;

    public LaomiGameApi(Activity mactivity, X5WebView webview) {
        this.mActivity = mactivity;
        this.mWebView = webview;
    }
	public LaomiGameApi(Activity mactivity) {
		this.mActivity = mactivity;

	}


//弹提示

    /**
     * 弹系统提示
     * @param msg
     */
    @JavascriptInterface
	public  void showToast(final String msg){
        mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(mActivity,msg,Toast.LENGTH_LONG).show();
            }
        });




	}

    /**
     * 退出程序
     */
    @JavascriptInterface
    public  void exit( ){

        mActivity.finish();
       // Toast.makeText(mActivity,msg,Toast.LENGTH_LONG).show();

     //   mWebView.loadUrl("javascript:LaomiGameCallBack.uploadresult(" + 1111 + ")");

    }




    /**
     * 添加下载任务
     * @param gameid
     * @param gamename
     * @param gameurl
     * @param gameiconurl
     * @param packageme
     */
    @JavascriptInterface
    public void addDownloadTask( String gameid, String gamename,String gameurl,String gameiconurl,String packageme) {
        Yayalog.loger("gameapisetdata:"+packageme);
        //如果安装了当前包，直接跳往该应用
       if (checkAppInstalled(packageme)){

           PackageManager packageManager = mActivity.getPackageManager();

           Intent intent =packageManager.getLaunchIntentForPackage(packageme);

           if(intent==null){
               System.out.println("APP not found!");
           }

           mActivity.startActivity(intent);

       }else {
           //如果没有安装跳往下载安装界面
           Intent intent = new Intent(mActivity, TasksManagerActivity.class);
           intent.putExtra("gameid",gameid);
           intent.putExtra("gamename",gamename);
           intent.putExtra("gameurl",gameurl);
           intent.putExtra("gameiconurl",gameiconurl);
           intent.putExtra("gamepackagename",packageme);
           mActivity.startActivity(intent);
       }

    }

    /**
     * 通过包名获取是否安装当前app
     * @param pkgName
     * @return
     */
    @JavascriptInterface
    public boolean checkAppInstalled(String pkgName) {
        Log.e("yayalog","checkAppInstalled"+pkgName);
        Yayalog.loger("checkAppInstalled");

        if (pkgName== null || pkgName.isEmpty()) {
            return false;
        }
        PackageInfo packageInfo;
        try {
            packageInfo = mActivity.getPackageManager().getPackageInfo(pkgName, 0);
        } catch (PackageManager.NameNotFoundException e) {
            packageInfo = null;
           // e.printStackTrace();
        }
        if(packageInfo == null) {
            return false;
        } else {
            return true;//true为安装了，false为未安装
        }
    }

    /**
     * 前往 下载界面
     */
    @JavascriptInterface
    public void goToDownloadTask() {
        Yayalog.loger("gameapisetdata:");
        Intent intent = new Intent(mActivity, TasksManagerActivity.class);

        mActivity.startActivity(intent);
    }

    /**
     * 以key  value形式保存数据到本地
     * @param key
     * @param valuemsg
     */
    @JavascriptInterface
    public void saveStringToLocal( String key,String valuemsg) {
        Sputils.putSPstring(key,valuemsg,mActivity);

    }

    /**
     *  使用key获取保存到本地的值，如果没有保存过则返回 default 默认值
     * @param key
     * @param defaultvalue
     * @return
     */
    @JavascriptInterface
    public String getStringFromLocal( String key,String defaultvalue) {
        final String value=Sputils.getSPstring(key,defaultvalue,mActivity);

        return value;
    }


    //设备号

    /**
     * 获取oaid
     * @return
     */
    @JavascriptInterface
    public String getOaid() {
        Log.d("gameapi","getOaid1"
                +App.oaid);


        // WebViewActivity.getOaid();
        return App.oaid +"app";


    }

    String imei="22";
    //设备号

    /**
     * 获取imei
     * @return
     */
    @JavascriptInterface
    public String getImei() {

        //设备号
        Acp.getInstance(mActivity).request(new AcpOptions.Builder()
                        .setPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE
                                , Manifest.permission.READ_PHONE_STATE
                                )
                        /*以下为自定义提示语、按钮文字
                        .setDeniedMessage()
                        .setDeniedCloseBtn()
                        .setDeniedSettingBtn()
                        .setRationalMessage()
                        .setRationalBtn()*/
                        .build(),
                new AcpListener() {
                    @Override
                    public void onGranted() {
                       // writeSD();
                        //getIMEI();

                          imei=   DeviceUtil.getIMEI(mActivity);
                        Toast.makeText(mActivity,imei,Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onDenied(List<String> permissions) {
                        //makeText(permissions.toString() + "权限拒绝");
                    }
                });
        return imei;
    }


    /**
     * 设置安装后删除  0 为不删，1为删
     * @param key
     */
    //安装后删除  0 为不删，1为删
    @JavascriptInterface
    public void setIsInstallApkDelete(int key) {
        boolean b = Sputils.putSPint(Constant.ISINSTALLAPKDELETE, key, mActivity);


    }

    /**
     * 安装后删除  0 为不删，1为删
     * @return
     */
    //安装后删除  0 为不删，1为删
    @JavascriptInterface
    public int getIsInstallApkDelete() {
      final int b=  Sputils.getSPint(Constant.ISINSTALLAPKDELETE, 0, mActivity);
       // boolean b = Sputils.putSPint(Constant.ISINSTALLAPKDELETE, key, mActivity);


      return b;

    }

    /**
     * 设置自动安装  0 为不装，1为装
     * @param key
     */
    //自动安装  0 为不装，1为装
    @JavascriptInterface
    public void setIsAutoInstallApk(int key) {
        boolean b = Sputils.putSPint(Constant.ISAUTOINSTALLAPK, key, mActivity);


    }

    /**
     * 自动安装  0 为不装，1为装
     * @return
     */
    //自动安装  0 为不装，1为装
    @JavascriptInterface
    public int getIsAutoInstallApk() {
        final int b=  Sputils.getSPint(Constant.ISAUTOINSTALLAPK, 0, mActivity);
        // boolean b = Sputils.putSPint(Constant.ISINSTALLAPKDELETE, key, mActivity);


        return b;
    }

    /**
     * 获取appid
     * @return
     */
    @JavascriptInterface
    public String getAppid() {


        return DeviceUtil.getAppid(mActivity);
    }

    /**
     * 获取应用程序版本号
     * @return
     */
    @JavascriptInterface
    public int getVersionCode() {
        Yayalog.loger("java getVersioncode");
        try {
            PackageManager packageManager = mActivity.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    mActivity.getPackageName(), 0);
            Yayalog.loger("java getVersioncode"+packageInfo.versionCode);
            return packageInfo.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }


        return 0;

    }

    /**
     * [获取应用程序版本名称信息]
     * @return 当前应用的版本名称
     */
    @JavascriptInterface
    public  String getVersionName() {
        try {
            PackageManager packageManager = mActivity.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    mActivity.getPackageName(), 0);
            return packageInfo.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "0";
    }


    public  void shareImage( Uri uri) {

        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("image/*");
        intent.putExtra(Intent.EXTRA_STREAM, uri);
        mActivity.startActivity(Intent.createChooser(intent, "分享到"));
    }
    //系统分享
    @JavascriptInterface
    public  void shareText(String text) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT, text);
        mActivity.startActivity(Intent.createChooser(intent, "分享到"));
    }


    String  TAG="jiafan";



    /**
     * 上传图片
     * @param imagePath
     */
    private void uploadImage(String imagePath,String appid,String uid,String token) {
        doPost(imagePath,appid,uid,token);

    }

    public static String url="";

    private void doPost(String imagePath,String appid ,String uid,String token) {

     RequestParams params = new RequestParams("https://api.kingoo.com.cn/user/upload_icon/");
        // params.setSslSocketFactory(...); // 如果需要自定义SSL
        // params.addQueryStringParameter("wd", "xUtils");
        params.addQueryStringParameter("app_id", appid);
        params.addQueryStringParameter("token", token);
        params.addQueryStringParameter("uid", uid);
        params.setMultipart(true);
        params.addBodyParameter("upfile", new File(imagePath),"image/jpeg");

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
               // Toast.makeText(x.app(), result, Toast.LENGTH_LONG).show();
                Log.e("photo",result);
                mWebView.evaluateJavascript("javascript:LaomiGameCallBack.uploadresult(" + result.toString() + ")");
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Toast.makeText(x.app(), ex.getMessage(), Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {

            }
        });



    }



    /**
     * 测试方法不使用
     */
    @JavascriptInterface
    public  void getTest(String name ){

        mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Yayalog.loger("javascript:"+name+".test()");
                mWebView.loadUrl("javascript:"+name+".test()");
            }
        });


    }

    /**
     * 测试方法不使用
     */
    @JavascriptInterface
    public  void getTest2( ){

        //mActivity.finish();
        // Toast.makeText(mActivity,msg,Toast.LENGTH_LONG).show();

        //   mWebView.loadUrl("javascript:LaomiGameCallBack.uploadresult(" + 1111 + ")");

    }
    /**
     * 测试方法不使用
     */
    //异步API
    @JavascriptInterface
    public void test3() {
        Yayalog.loger("test3");
        String conbackstring="LaomiGameBridge.apicallback('sendPhoto',{err_code:100})";
        mWebView.evaluateJavascript("javascript:"+conbackstring);
      //  mWebView.evaluateJavascript("javascript:LaomiGameBridge.success('JavascriptInterfacetest3')");
    }

}
